<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户端 - 点餐系统</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f7f7f7;
        }

        .container {
<!--            max-width: 800px;-->
<!--            margin: 20px auto;-->
<!--            background-color: #fff;-->
<!--            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);-->

            background-color: rgba(255, 255, 255, 0.8); /* 背景色透明度，可根据需要调整 */
            padding: 40px;
            border-radius: 8px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
            text-align: center;
            margin: auto; /* 居中 */
            overflow: hidden; /* 防止内容溢出 */

            background-image: url('../static/img/baoshijie.jpg');
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat; /* 防止图片重复 */
            height: 100vh; /* 降低高度，使布局看起来更均衡 */
            width: 100%;
            display: flex;
            flex-direction: column; /* 竖直布局 */
            align-items: center;
            justify-content: center;
            border: 10px solid rgba(255, 255, 255, 0.5); /* 透明边框 */
        }

        .content {
            background-color: rgba(255, 255, 255, 0.8);
            padding: 40px; /* 增加内边距 */
            border-radius: 15px; /* 增加边框圆角 */
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
            margin: 20px; /* 增加外边距 */
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        th, td {
            border: 1px solid #ddd;
            padding: 12px;
            text-align: left;
        }

        th {
            background-color: #4caf50;
            color: white;
        }

        h1 {
            color: #333;
            text-align: center;
            margin-top: 30px;
        }

        .order-btn {
            background-color: #4caf50;
            color: white;
            padding: 10px 15px;
            border: none;
            cursor: pointer;
            font-size: 16px;
            margin-top: 10px;
        }

        .form-popup {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #fefefe;
            padding: 20px;
            border: 1px solid #ddd;
            z-index: 9;
            border-radius: 8px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
        }

        .form-container {
            max-width: 300px;
            margin: auto;
        }

        .form-container input {
            width: 100%;
            padding: 10px;
            margin: 5px 0 10px 0;
            display: inline-block;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
        }

        .form-container button {
            background-color: #4caf50;
            color: white;
            padding: 10px 15px;
            border: none;
            cursor: pointer;
            border-radius: 4px;
        }

        .close-btn {
            color: #4caf50;
            float: right;
            font-size: 20px;
            cursor: pointer;
        }


    </style>
</head>
<body>

    <div class="container">
        <div class="content">
            <h1>欢迎使用点餐系统，{{ username }}！</h1>
            <button class="order-btn" onclick="openForm('modUserForm')">修改我的信息</button>
            <button class="order-btn" onclick="openWalletFormAndShowAccount()" type="submit">我的钱包</button>
            <button class="order-btn" onclick="openForm('myOrderForm')" type="submit">我的订单</button>
            <button class="order-btn" onclick="decliningSales()" type="submit">销量降序</button>
            <button class="order-btn" onclick="openForm('findDishForm')" type="submit">查询菜品</button>
            <button class="order-btn" onclick="logout()" type="submit">退出登录</button>
            <form action="/user/dashboard" method="post">
                <h2>菜品列表</h2>
                <table>
                    <tr>
                        <th>菜品编号</th>
                        <th>菜名</th>
                        <th>价格</th>
                        <th>销量</th>
                        <th>库存</th>
                        <th>加入菜单</th>
                    </tr>
                        {% for dish in dishes %}
                            <tr>
                                <td >{{ dish.Did}}</td>
                                <td>{{ dish.Dname}}</td>
                                <td>{{ dish.Dprice}}</td>
                                <td id=sale{{dish.Did}}>{{ dish.Dsale}}</td>
                                <td id=dinv{{dish.Did}}>{{ dish.Dinv}}</td>
                                <td><button type="button" onclick="addToCart('{{ dish.Did }}', '{{ dish.Dname }}',
                                 '{{ dish.Dprice }}', '{{ dish.Dsale }}', '{{ dish.Dinv }}')">加菜</button></td>
                            </tr>
                        {% endfor %}
                    <!-- 添加更多菜品行 -->
                </table>
                <h2>已选菜品</h2>
                <table id="cartTable">
                    <tr>
                        <th>菜品编号</th>
                        <th>菜名</th>
                        <th>价格</th>
                        <th>操作</th>
                    </tr>
                    <!-- 这里将显示用户已选的菜品 -->
                </table>
            </form>
            <button class="order-btn" onclick="purchasable()" type="submit">下单</button>
        </div>
    </div>


    <!--------------------------------修改用户信息------------------------------------------->
    <div class="form-popup" id="modUserForm">
        <div class="form-container">
            <span class="close-btn" onclick="closeForm('modUserForm')">&times;</span>
            <h2>请输入新的信息</h2>
                <input type="text" placeholder="新的姓名" id="name">
                <input type="text" placeholder="新的用户名" id="username">
                <input type="password" placeholder="新的密码" id="password">
                <input type="text" placeholder="新的电话号码" id="phone">
                <button onclick="modUser()">确认修改</button>
        </div>
    </div>
    <!--------------------------------修改用户信息------------------------------------------->

    <!--------------------------------我的钱包------------------------------------------->
    <div class="form-popup" id="userWalletForm">
        <div class="form-container">
            <span class="close-btn" onclick="closeForm('userWalletForm')">&times;</span>
            <h2>当前您的账户有<span id="accountValue"></span>元</h2>
            <h3>请输入要充值的金额</h3>
                <input type="text" placeholder="请输入要充值的金额" id="account">
                <button onclick="wallet()">确认充值</button>
        </div>
    </div>
    <!--------------------------------我的钱包------------------------------------------->

    <!--------------------------------查询菜品------------------------------------------->
    <div class="form-popup" id="findDishForm">
        <div class="form-container">
            <span class="close-btn" onclick="closeForm('findDishForm')">&times;</span>
            <h2>请输入您要查询的菜品</h2>
            <input type="text" placeholder="请输入要查询的菜品" id="findDish">
            <button onclick="searchDish()">确认查询</button>
            <!-- 添加一个表格用于显示查询结果 -->
            <table id="searchResultTable">
                <tr>
                    <th>菜品编号</th>
                    <th>菜名</th>
                    <th>价格</th>
                    <th>销量</th>
                    <th>库存</th>
                    <th>加入菜单</th>
                </tr>
            </table>
        </div>
    </div>
    <!--------------------------------查询菜品------------------------------------------->

    <!--------------------------------我的订单------------------------------------------->
    <div class="form-popup" id="myOrderForm">
        <div class="form-container">
            <span class="close-btn" onclick="closeForm('myOrderForm')">&times;</span>
            <h2>你的订单</h2>
            <button onclick="submitMyOrderForm()">点击查看</button>
                <table>
                    <tr>
                        <th>订单编号</th>
                        <th>菜名</th>
                        <th>价格</th>
                    </tr>
                </table>
                <table id="orderTable">
                    <!-- 这里将显示我的订单数据 -->
                </table>

        </div>
    </div>
    <!--------------------------------我的订单------------------------------------------>

    <script>

        <!--登出操作-->
        function logout() {
            result = window.confirm("确认退出登录？");
            if (result == true){
                // 在这里执行页面跳转到/
                window.location.href = '/';
            }
        }


        <!--添加菜品操作-->
        const cart = [];

        function addToCart(id, name, price, sale, inv) {
            document.querySelector(`#sale${id}`).innerHTML=+document.querySelector(`#sale${id}`).innerHTML+1
            document.querySelector(`#dinv${id}`).innerHTML=+document.querySelector(`#dinv${id}`).innerHTML-1

            const numericSale = parseInt(sale, 10) + 1;
            const numericInv = parseInt(inv, 10) - 1;
            const item = { id, name, price, sale: numericSale, inv: numericInv };
            cart.push(item);

            updateCartTable();
        }


        <!--更新已点菜单操作-->
        function updateCartTable() {
            const cartTable = document.getElementById('cartTable');

            cartTable.innerHTML = `<tr><th>菜品编号</th><th>菜名</th><th>价格</th><th>操作</th></tr>` +
                cart.map(item => `<tr><td>${item.id}</td><td>${item.name}</td><td>${item.price}</td>` +
                `<td><button onclick="removeFromCart('${item.id}')">移除</button></td></tr>`).join('');
        }


        <!--移除菜品操作-->
        function removeFromCart(id) {
            document.querySelector(`#sale${id}`).innerHTML=+document.querySelector(`#sale${id}`).innerHTML-1
            document.querySelector(`#dinv${id}`).innerHTML=+document.querySelector(`#dinv${id}`).innerHTML+1
            const index = cart.findIndex(item => item.id === id);
            if (index !== -1) {
                cart.splice(index, 1);
                updateCartTable();
            }
        }


        <!--下单操作-->
        <!--首先检查是否有足够的金额下单-->
        function purchasable() {
            const totalPrice = cart.reduce((sum, item) => sum + parseFloat(item.price), 0);
            const Check = "{{ username }}";
            const data = {
                total_price : totalPrice,
                check : Check
            }
            fetch('/purchasable', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
            })
            .then(response => response.json())
            .then(data => {
                console.log(data)
                if (data.status === 'success') {
                    placeOrder(); // 返回值为success，执行下单操作
                }
                if (data.status === 'error') {
                    alert('您的余额不足，请充值！');
                }
<!--                else {-->
<!--                    alert('下单时发生错误，请稍后重试。');-->
<!--                }-->
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }

        <!--余额充足，执行下单操作-->
        function placeOrder() {
            fetch('/place_order', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(cart),  // 将购物车信息以 JSON 格式发送给后端
            })
            .then(response => response.json())
            .then(data => {
            console.log(data)
                if (data.status === 'success') {
                    alert('订单已下达！感谢您的订购。');
                    // 清空购物车
                    cart.length = 0;
                    updateCartTable();
                } else {
                    alert('下单失败：' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
<!--                alert('下单时发生错误，请稍后重试。');-->
                alert('订单已下达！感谢您的订购。');
                updateCartTable();
            });
            window.location.reload(true);
        }



        <!--表格-->
        function openForm(formId) {
            document.getElementById(formId).style.display = 'block';
        }

        function closeForm(formId) {
            document.getElementById(formId).style.display = 'none';
        }

        <!--修改用户操作-->
        function modUser() {
            const newName = document.getElementById('name').value;
            const newUsername = document.getElementById('username').value;
            const newPassword = document.getElementById('password').value;
            const newPhone = document.getElementById('phone').value;
            const Check = "{{ username }}";

            const data = {
                name : newName,
                username : newUsername,
                password : newPassword,
                phone : newPhone,
                check : Check
            }

            fetch('/mod_user',{
             method:"post",
             body: JSON.stringify(data),
                headers: {
                'Content-Type': 'application/json'
                }
             })
                .then(response => response.json()).
                then(res=>{console.log(res);
                if (res.status === 'success') {
                // 跳转到 /login 页面
                window.location.href = '/login';
                window.alert("用户信息修改成功，请使用新的用户名和密码登录！");}
                })
                .catch(error => console.error('Error:', error))
                .finally(() => {
                // 关闭表单
                closeForm('modUserForm');
                });
        }
        <!--修改用户操作------------------------------------------------>

        <!--我的钱包-->
        function openWalletFormAndShowAccount() {
            show_account();
            openForm('userWalletForm');
        }

        <!--显示当前存款-->
        function show_account() {
            const Check = "{{ username }}";

            const data = {
                check : Check
            }

            fetch('/show_account',{
             method:"post",
             body: JSON.stringify(data),
                headers: {
                'Content-Type': 'application/json'
                }
             })
                .then(response => response.json())
                .then(res=>{console.log(res);
                if (res.status === 'success') {
                    const currentAccount = parseFloat(res.account);
                    document.getElementById('accountValue').innerText = currentAccount; // 界面显示当前存款
                    console.log(res);
                    }
                })
                .catch(error => console.error('Error:', error))
             closeForm('modUserForm');
        }


        <!--充值并更新显示-->
        function wallet() {
            const Account = document.getElementById('account').value;
            const Check = "{{ username }}";

            const data = {
                account : Account,
                check : Check
            }

            fetch('/wallet',{
             method:"post",
             body: JSON.stringify(data),
                headers: {
                'Content-Type': 'application/json'
                }
             })
                .then(response => response.json()).
                then(res=>{console.log(res);
                if (res.status === 'success') {
                    const newAccount = parseFloat(res.newAccount);
                    if (!isNaN(newAccount)) {
                        window.alert("充值成功！");
                        account = account + newAccount;
                        document.getElementById('accountValue').innerText = account; // 更新界面的当前存款
                    }
                    else {
                        console.error('Error: Invalid newAccount value');
                    }
                }
             })
                .catch(error => console.error('Error:', error))
                .finally(() => {
                // 关闭表单
                closeForm('userWalletForm');
                });
        }


        <!--我的订单展示-->
        function submitMyOrderForm() {

            const Check = "{{ username }}";

            var data = {
                check: Check
            };

            // 使用fetch发送POST请求
            fetch('/my_order', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
            })
            .then(response => response.json())
            .then(data => {
                // 处理响应数据
                console.log(data);
                const orderTable = document.getElementById('orderTable');

                // 清空表格内容
                orderTable.innerHTML = '';

                if (data && Array.isArray(data)) {
                    // 遍历订单数据并添加到表格中
                    data.forEach(order => {
                        const row = orderTable.insertRow();
                        const cell1 = row.insertCell(0);
                        const cell2 = row.insertCell(1);
                        const cell3 = row.insertCell(2);

                        cell1.innerHTML = order.Oid;
                        cell2.innerHTML = order.Oname;
                        cell3.innerHTML = order.Oprice;
                    });
                } else {
                    console.error('Error: Missing or invalid data in the response.');
                }
            })
            .catch(error => {
                // 处理错误
                console.error('Error:', error);
            });
        }

        <!--销量降序-->
        function decliningSales() {
            var table, rows, switching, i, x, y, shouldSwitch;
            table = document.querySelector("table"); // 获取表格
            switching = true;

            while (switching) {
                switching = false;
                rows = table.rows;

                for (i = 1; i < rows.length - 1; i++) {
                    shouldSwitch = false;

                    x = rows[i].querySelector("[id^='sale']"); // 获取销量列
                    y = rows[i + 1].querySelector("[id^='sale']");

                    // 将销量转换为数字进行比较
                    if (parseInt(x.textContent) < parseInt(y.textContent)) {
                        shouldSwitch = true;
                        break;
                    }
                }

                if (shouldSwitch) {
                    rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
                    switching = true;
                }
            }
        }

        <!--查询菜品-->
        function searchDish() {
            const keyword = document.getElementById('findDish').value;

            // 发送POST请求到服务器端进行查询
            fetch('/search_dish', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ keyword }),
            })
            .then(response => response.json())
            .then(data => {
                // 处理查询结果并显示在表格中
                displaySearchResults(data);
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }

        // 添加一个函数用于显示查询结果
        function displaySearchResults(results) {
            const searchResultTable = document.getElementById('searchResultTable');

            // 清空表格内容
            searchResultTable.innerHTML = '<tr><th>菜品编号</th><th>菜名</th><th>价格</th><th>销量</th><th>库存</th><th>加入菜单</th></tr>';

            // 显示查询结果
            results.forEach(dish => {
                const row = searchResultTable.insertRow();
                const cell1 = row.insertCell(0);
                const cell2 = row.insertCell(1);
                const cell3 = row.insertCell(2);
                const cell4 = row.insertCell(3);
                const cell5 = row.insertCell(4);
                const cell6 = row.insertCell(5);

                cell1.innerHTML = dish.Did;
                cell2.innerHTML = dish.Dname;
                cell3.innerHTML = dish.Dprice;
                cell4.innerHTML = dish.Dsale;
                cell5.innerHTML = dish.Dinv;
                cell6.innerHTML = `<button onclick="addToCart('${dish.Did}', '${dish.Dname}', '${dish.Dprice}', '${dish.Dsale}', '${dish.Dinv}')">加菜</button>`;
            });
        }

    </script>

</body>
</html>
